/*
 * TallActivity is an alternate format for WideActivity. This is not currently used & 
 * is just a placeholder for the time being.
 */
package com.example.wmuqrreader;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.R.integer;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class TallActivity extends Activity {
    
	DatabaseHandler db;
	
	Spinner spinner;
	Spinner spinner_brand;
	Spinner spinner_type;
	
	String inventory_id = "-1";
	String building_id;
	
	Button button_scan;		
	Button button_save; 	
	Button button_newa;	
	Button button_service;
	
	EditText editText_qr;
	EditText editText_inv;
	EditText editText_location;
	EditText editText_sn;
	EditText editText_type;
	EditText editText_brand;
	EditText editText_yr;
	EditText editText_svDate;
	EditText editText_intvl;
	
	Bundle extras;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tall);
        
        db = new DatabaseHandler(this);
        
        spinner 			= (Spinner) findViewById(R.id.spinner_buildingList);
        spinner_brand		= (Spinner) findViewById(R.id.spinner_brand);
        spinner_type		= (Spinner) findViewById(R.id.spinner_type);
        
        //Buttons - need functions
  		button_scan 		= (Button) findViewById(R.id.btn_scan);
  	    button_save 		= (Button) findViewById(R.id.btn_save);
  	    button_newa 		= (Button) findViewById(R.id.btn_new);
  	    button_service		= (Button) findViewById(R.id.btn_service);
  	    
  	    //Fields - will be populated later
  	    editText_qr			= (EditText) findViewById(R.id.editText_qrNumber);
  	    editText_inv 		= (EditText) findViewById(R.id.editText_invNumber);
  	    editText_location	= (EditText) findViewById(R.id.editText_location);
  	    editText_sn			= (EditText) findViewById(R.id.editText_buildingName);
  	    editText_yr			= (EditText) findViewById(R.id.editText_manfacDate);
  	    editText_svDate		= (EditText) findViewById(R.id.editText_lastService);
  	    editText_intvl		= (EditText) findViewById(R.id.editText_serviceInterval);

  	    extras = getIntent().getExtras();
  	    
        List<String> buildings = new ArrayList<String>();
        buildings = db.getAllBuildingNames();
        
        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, buildings);
 
        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
        
        spinner_type.setPrompt("Select Type");
        spinner_brand.setPrompt("Select Brand");
        
    	//Set default focus to QR field
	    editText_qr.requestFocus();
	    
        //ID Passed - existing inventory
        if (extras.getString("ID") != null )
        {
        	inventory_id = extras.getString("ID");
        	Log.d("GOT ID: ", inventory_id);
        	
        	populateFields(inventory_id); 
			
			button_scan.setText("Delete");
			editText_qr.setHint("NOTICE: Changing the QR# will reset any existing service records!");
			
			//Add a function for the SCAN button (renamed DELETE) click
            button_scan.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				ConfirmInvDelete();      
    			}
    		});
        }
        //No ID passed - new inventory
        else
        {
    	    
        	//Set hint for service date
        	editText_svDate.setHint("No inspection on file");
    	    
    	    if(extras.getString("SCAN") != null)
    	    {
    	    	inventory_id = String.format("%5s:", extras.getString("QR") ).replace(' ', '0');
    	    	Log.d("GOT QR: ", inventory_id);
    	    	
    	    	editText_inv.setText(inventory_id);
    	    }    	        	   
    	    
    	    //Add a function for the SCAN button click
            button_scan.setOnClickListener(new View.OnClickListener() {
                            
                    @Override
                    public void onClick(View v) {
                            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                            intent.setPackage("com.google.zxing.client.android");
                            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                            
                            startActivityForResult(intent, 0);                              
                    }
             });
        } 
        
        if (extras.getString("BUILDING") != null )
        {
        	building_id = extras.getString("BUILDING");
        	Log.d("GOT BUILDING: ", building_id);
        	
        	String gotBldg = db.getBuilding(Integer.parseInt(building_id)).get_building();
        	
        	// set the selected value of the spinner
            spinner.setSelection(dataAdapter.getPosition(gotBldg));
        }   
        
        //Add a function for the SAVE button click
        button_save.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				
				Inventory newInv = populateInventory(0);
				if(newInv._qr > 0)
				{
					//If exists, update, else add
					if (extras.getString("ID") != null )
					{
						if( db.updateInventory( populateInventory( Integer.parseInt(extras.getString("ID")) ) )	> 0)
						{
							Toast.makeText(getApplicationContext(), "Changes saved successfully", Toast.LENGTH_LONG).show();
							
							setResult(RESULT_OK, null);
							finish();
						}
						else
							editText_qr.setError("An inventory item with QR# " + newInv._qr + " has already been added to the database");
					}
					else
					{						
						if(newInv._qr > 0)
						{
							if(db.addInventory(newInv) > 0)
							{
								Toast.makeText(getApplicationContext(), "New entry saved successfully", Toast.LENGTH_LONG).show();						
						        setResult(RESULT_OK, null);
								finish();
							}
							else 
								editText_qr.setError("An inventory item with QR# " + newInv._qr + " has already been added to the database");
						}	
					}
				}
				else
					editText_qr.setError("An valid QR number greater than 0 is required");
			}
		});
        
        //Add a function for the SERVICE button click        
        button_service.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {			
					
					//Validate QR #
					if(editText_qr.getText().toString().trim().length() >= 1)
					{		
						Inventory chkInv = db.getInventory(Integer.parseInt(editText_qr.getText().toString()), "");
						
						if(chkInv._inv < 0 || chkInv._id == Integer.parseInt(inventory_id))
						{
							Intent intent = new Intent();
							
							intent.putExtra("ID", editText_qr.getText().toString());
							
							intent.setClass(TallActivity.this, InspectionActivity.class);
					        startActivityForResult(intent,1);
						}
						else
							editText_qr.setError("An inventory item with QR# " + editText_qr.getText().toString() + " has already been added to the database");
					}
					else
					{
						editText_qr.setError( "A valid QR number is required" ); 
					}
					
				}
		});
  	    
    }

	//Populate the TallActivity fields from a given Inventory
	private void populateFields(String inventory_id) {
		
		Inventory entry = db.getInventory( Integer.parseInt(inventory_id) );		
		    	
    	editText_qr.setText( Integer.toString(entry.get_qr()));
    	if(entry.get_inv() > 0)
    	{
    		editText_inv.setText( Integer.toString(entry.get_inv()) ); 
    	}

		editText_location.setText( entry.get_location() );
		editText_sn.setText( entry.get_serialNum() );
		spinner_type.setSelection(getIndex(spinner_type, entry.get_type()));
		spinner_brand.setSelection(getIndex(spinner_brand, entry.get_brand()));
		editText_yr.setText( entry.get_year() );
		editText_svDate.setText( entry.get_svDate() );
		editText_intvl.setText( Integer.toString( entry.get_interval()) ); //TODO: what do??
	}
	
	//Locate a value in the dropdown list - or, default to the first value
	private int getIndex(Spinner spinner, String myString)
	{	
		for(int i = 0; i < spinner.getCount(); i++)
		{
			if(spinner.getItemAtPosition(i).equals(myString))
				return i;
		}
		
		return 0;
	}
	
	//Populate a new inventory object from field data
	private Inventory populateInventory(int id)
	{		
		int bldg 		= 0;
		String loc		= editText_location.getText().toString();
		String sn		= editText_sn.getText().toString();
		String type 	= spinner_type.getSelectedItem().toString();
		String brand 	= spinner_brand.getSelectedItem().toString();
		String sd 		= editText_svDate.getText().toString();
		String yr 		= editText_yr.getText().toString();
		String tempInv 	= editText_inv.getText().toString();
		String tempQr	= editText_qr.getText().toString();
		String tempIntvl= editText_intvl.getText().toString();
		int qr			= Integer.MIN_VALUE;
		int inv			= Integer.MIN_VALUE;
		int intvl		= Integer.MIN_VALUE;
		
		//Validate QR #
		if(tempQr.length() >= 1)
		{
			qr = Integer.parseInt( tempQr );
		}
		else
		{
			editText_qr.setError( "A valid QR number is required" ); 
		    return new Inventory();
		}
		
		//Validate Inventory #
		if(tempInv.length() > 1)
			inv = Integer.parseInt(tempInv);
				
		
		if(!tempIntvl.matches(""))
			intvl = Integer.parseInt(tempIntvl);
		
		
		//fetch building based on spinner selection
		bldg = db.getBuilding(spinner.getSelectedItem().toString());
		
		//If there is no building id, the inventory will be added to NEW STOCK
		if(building_id != null && bldg < 1){
			bldg		= Integer.parseInt(building_id);	
		}
				
		if(id > 0) {	return new Inventory(id, loc, sn, type, brand, sd, yr, inv, qr, bldg, intvl);	}
		else {	return new Inventory(loc, sn, type, brand, sd, yr, inv, qr, bldg, intvl);	}
	}  
	
	private void ConfirmInvDelete()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Delete Inventory " + editText_qr.getText().toString())
        .setMessage("Deleting an inventory entry cannot be undone! All inventory details and associated service records will be destroyed. "
        		+ "Are you sure you wish to proceed? ")
        .setNegativeButton("No", null)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	        	
	        	Inventory delInv = populateInventory(Integer.parseInt(inventory_id));
				db.deleteInventory(delInv);
				
				Toast.makeText(getApplicationContext(), "Entry destroyed", Toast.LENGTH_LONG).show();
				
				setResult(RESULT_OK, null);
				finish();	   
	        }
	    })
	    .show();
	}
 
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) 
        {
            if (resultCode == RESULT_OK) 
            {
            	Inventory inventory_scan;            	
                String contents = intent.getStringExtra("SCAN_RESULT");   
                
                inventory_scan = db.getInventory( Integer.parseInt(contents), "QR" ); 
                if(inventory_scan.get_inv() == -1)
                {
                	Toast.makeText(getApplicationContext(), "Creating New...", Toast.LENGTH_LONG).show();
                	editText_qr.setText(contents);
                	
                	//Auto populate Service Date with today's date
            	    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            		Date date = new Date();
            		
            	    editText_svDate.setText(dateFormat.format(date));
                }
                else
                {
                	 Toast.makeText(getApplicationContext(), "Got: " + contents, Toast.LENGTH_LONG).show();
                	 populateFields(Integer.toString(inventory_scan.get_id()));
                }
                
            } 
            else if (resultCode == RESULT_CANCELED) 
            {
                // Handle cancel
            }
        }
        if (requestCode== 1)
        {
        	if(resultCode == RESULT_OK)
        	{
        	    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        		Date date = new Date();
        		
        	    editText_svDate.setText(dateFormat.format(date));
        	}
        }
    }
    
}
